package com.rocky.server.timer;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import org.apache.log4j.Logger;

import com.rocky.server.Global;
import com.rocky.server.database.DBAdapter;

public class MetPointTimer implements Runnable {
	private static Logger logger = Logger.getLogger(MetPointTimer.class);
	boolean lock = false;

	public void run() {
		logger.debug("Met point timer start.");
		while(true){
			logger.debug("Met point timer run.");
			if(!lock){
				lock = true;
				HashMap<String,Set<Integer>> tempPointList = (HashMap<String, Set<Integer>>) Global.pointList.clone();
				Global.pointList.clear();
				StringBuilder sbSql = new StringBuilder();
				DBAdapter db = new DBAdapter();
				try {
					String selectSql = "select * from point ";
					db.rs = db.stmt.executeQuery(selectSql);
					while(db.rs.next()){
						int userid = db.rs.getInt("userid");
						String location_key = db.rs.getString("location_key");
						String location = db.rs.getString("location");
						if(tempPointList.get(location_key)!=null && tempPointList.get(location_key).size() > 0){
							Iterator<Integer> tempUserIterator = tempPointList.get(location_key).iterator();
							while(tempUserIterator.hasNext()){
								int tempUserid = tempUserIterator.next();
								if(tempUserid != userid){
									sbSql.append("insert into message (fromuserid,touserid,msg,time,type) values ("+tempUserid+","+userid+",'"+location+"',now(),1);");
								}
							}
						}
					}
					logger.debug("*********************************");
					logger.debug(sbSql.toString());
					logger.debug("*********************************");
					if(sbSql.length() > 0){
						db.stmt.executeUpdate(sbSql.toString());
					}
				} catch (SQLException e) {
					logger.error(e.toString());
				}finally{
					db.closeConnect();
				}
				lock = false;
			}
			try {
				Thread.sleep(60*1000);
			} catch (InterruptedException e) {
				logger.error(e.toString());
			}
		}
	}

}
